package com.wyzz.hr.bo.impl;

import java.util.Date;
import java.util.List;
import org.apache.axis.utils.StringUtils;
import org.hibernate.FetchMode;
import org.hibernate.criterion.*;

import com.wyzz.hr.base.FileOperate;
import com.wyzz.hr.base.Status;
import com.wyzz.hr.bo.IEmpContractBo;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.dao.IEmpContractDao;
import com.wyzz.hr.pojo.Empcontract;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.DateUtil;
import com.wyzz.hr.util.Pager;

public class EmpContractBoImpl implements IEmpContractBo, Status {

	public EmpContractBoImpl() {
	}

	public boolean saveContract(Empcontract contract) {
		try {
			empContractDao.saveObject(contract);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public List searchByEmpNo(String empNo) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Empcontract.class);
		detachedCriteria.setFetchMode(Empcontract.PROP_EMPLOYEE,
				FetchMode.DEFAULT);
		detachedCriteria.setFetchMode(Empcontract.PROP_CONTRACT_TYPE,
				FetchMode.JOIN);
		detachedCriteria.add(Restrictions.eq((new StringBuilder()).append(
				Empcontract.PROP_EMPLOYEE).append(".").append(Employee.PROP_ID)
				.toString(), empNo));
		detachedCriteria.addOrder(Order.desc(Empcontract.PROP_ECT_START_DATE));
		List result = empContractDao.findByCriteria(detachedCriteria);
		return result;
	}

	public List findContract(DetachedCriteria dc, Pager page,
			String searchOrExport) {
		if (page == null || "export".equals(searchOrExport)) {
			return empContractDao.findByCriteria(dc);
		} else {
			page.splitPage(dc);
			return empContractDao.findByCriteria(dc, page.getPageSize(), page
					.getCurrentPage());
		}
	}

	public List findContractByEmp(DetachedCriteria dc, Pager page,
			String searchOrExport) {
		if (page == null || "export".equals(searchOrExport)) {
			return empContractDao.findByCriteria(dc);
		} else {
			page.splitPage(dc);
			return empContractDao.findByCriteria(dc, page.getPageSize(), page
					.getCurrentPage());
		}
	}

	public Empcontract getById(String contractId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Empcontract.class);
		detachedCriteria.setFetchMode(Empcontract.PROP_EMPLOYEE,
				FetchMode.DEFAULT);
		detachedCriteria.setFetchMode(Empcontract.PROP_CONTRACT_TYPE,
				FetchMode.DEFAULT);
		detachedCriteria.add(Restrictions.eq(Empcontract.PROP_ECT_ID,
				contractId));
		List result = empContractDao.findByCriteria(detachedCriteria);
		if (result.size() == 0)
			return null;
		else
			return (Empcontract) result.get(0);
	}

	public String insert(Empcontract empContract) {
		String error = "";
		Employee e = (Employee) empContractDao.loadObject(
				com.wyzz.hr.pojo.Employee.class, empContract.getEmployee()
						.getId(), new String[] { "contract" }, new boolean[0]);
		Empcontract old = e.getContract();
		if (old != null) {
			Date newStartDate = empContract.getEctStartDate();
			if (!newStartDate.after(old.getEctStartDate())) {
				error = (new StringBuilder())
						.append(old.getEmployee().getEmpName())
						.append("\u4E8E")
						.append(DateUtil.formatDate(old.getEctStartDate()))
						.append(
								"\u7B7E\u7F72\u524D\u4E00\u4EFD\u5408\u540C\uFF0C\u65B0\u5408\u540C\u8D77\u59CB\u65E5\u671F\u5FC5\u987B\u665A\u4E8E\u6B64\u65E5\u671F\uFF01")
						.toString();
				return error;
			}
			old.setEctLastChangeBy(empContract.getEctLastChangeBy());
			old.setEctLastChangeTime(empContract.getEctLastChangeTime());
			old.setEctStatus("2");
			empContractDao.updateObject(old);
		}
		empContractDao.saveObject(empContract);
		return error;
	}

	public String delete(Empcontract ect) {
		String hql = (new StringBuilder()).append(
				"delete from Empcontract where ectId='").append(ect.getEctId())
				.append("'").toString();
		empContractDao.exeHql(hql);
		IEmployeeBo empBo = (IEmployeeBo) SpringBeanFactory.getBean("empBo");
		Employee emp = empBo.loadEmp(ect.getEmployee().getId(), null);
		List oldList = searchByEmpNo(emp.getId());
		if (oldList != null && oldList.size() > 0)
			emp.setContract((Empcontract) oldList.get(0));
		else
			emp.setContract(null);
		return (new StringBuilder()).append("\u5458\u5DE5").append(
				emp.getEmpName()).append(
				"\u7684\u5408\u540C\u5220\u9664\u6210\u529F\uFF01").toString();
	}

	public String update(Empcontract empContract, String ContractId,
			String comments) {
		Empcontract oldContract = getById(ContractId);
		if (empContract.getEctAttatchment() != null) {
			if (oldContract != null)
				FileOperate.deleteFile("sys.profile.file.path", oldContract
						.getEctAttatchment());
			oldContract.setEctAttatchment(empContract.getEctAttatchment());
		} else if (oldContract != null)
			empContract.setEctAttatchment(oldContract.getEctAttatchment());
		String error = "";
		Empcontract old = getLastContract(ContractId, empContract.getEmployee()
				.getId());
		if (old != null
				&& !old.getEctStartDate().before(empContract.getEctStartDate())) {
			error = (new StringBuilder())
					.append(oldContract.getEmployee().getEmpName())
					.append("\u4E8E")
					.append(DateUtil.formatDate(old.getEctStartDate()))
					.append(
							"\u7B7E\u7F72\u524D\u4E00\u4EFD\u5408\u540C\uFF0C\u65B0\u5408\u540C\u8D77\u59CB\u65E5\u671F\u5FC5\u987B\u665A\u4E8E\u6B64\u65E5\u671F\uFF01")
					.toString();
			return error;
		}
		oldContract.setEctNo(empContract.getEctNo());
		oldContract.setEctStartDate(empContract.getEctStartDate());
		oldContract.setEctEndDate(empContract.getEctEndDate());
		oldContract.setEtcExpire(empContract.getEtcExpire());
		if (!StringUtils.isEmpty(comments))
			oldContract.setEctComments((new StringBuilder()).append(
					empContract.getEctComments()).append("\n").append(comments)
					.toString());
		else
			oldContract.setEctComments(empContract.getEctComments());
		oldContract.setEctStatus(empContract.getEctStatus());
		oldContract.setEmployee(empContract.getEmployee());
		oldContract.setContractType(empContract.getContractType());
		oldContract.setEctLastChangeBy(empContract.getEctLastChangeBy());
		oldContract.setEctLastChangeTime(empContract.getEctLastChangeTime());
		empContractDao.saveOrupdate(oldContract);
		return error;
	}

	private Empcontract getLastContract(String id, String empId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Empcontract.class);
		detachedCriteria.add(Restrictions.ne("ectId", id));
		detachedCriteria.add(Restrictions.eq("employee.id", empId));
		detachedCriteria.addOrder(Order.desc("ectStartDate"));
		List list = empContractDao.findByCriteria(detachedCriteria);
		if (list != null && list.size() > 0)
			return (Empcontract) list.get(0);
		else
			return null;
	}

	public boolean deleteAttach(String contractId, String fileName) {
		try {
			FileOperate.deleteFile("sys.profile.file.path", fileName);
			String hql = (new StringBuilder()).append(
					"update Empcontract set ectAttatchment=null where ectId='")
					.append(contractId).append("'").toString();
			empContractDao.exeHql(hql);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public void checkOrderMethod(DetachedCriteria detachedCriteria, String order) {
		if (order != null && order.trim().length() > 1
				&& order.indexOf('-') != -1) {
			String pram[] = order.split("-");
			if (pram[0] == null || pram[0].length() < 1)
				detachedCriteria.addOrder(Order.desc(order));
			String orde = pram[0];
			if (orde != null && !"empJoinDate".equals(orde)) {
				if (pram.length == 2 && pram[1].equalsIgnoreCase("up"))
					detachedCriteria.addOrder(Order.asc(orde));
				else
					detachedCriteria.addOrder(Order.desc(orde));
			} else if ("empJoinDate".equals(orde))
				if (pram.length == 2 && pram[1].equalsIgnoreCase("up"))
					detachedCriteria.addOrder(Order.desc(orde));
				else
					detachedCriteria.addOrder(Order.asc(orde));
		}
		detachedCriteria.addOrder(Order.desc((new StringBuilder()).append(
				Employee.PROP_EMP_CONTRACT).append(".").append(
				Empcontract.PROP_ECT_END_DATE).toString()));
		detachedCriteria.addOrder(Order.asc("empDistinctNo"));
	}

	public List getContractListByEmp(Employee emp) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Empcontract.class);
		detachedCriteria.add(Restrictions.eq(Empcontract.PROP_EMPLOYEE, emp));
		detachedCriteria.addOrder(Order.asc(Empcontract.PROP_ECT_START_DATE));
		return empContractDao.findByCriteria(detachedCriteria);
	}

	public int hasConflictInTime(Empcontract contract) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Empcontract.class);
		detachedCriteria.add(Restrictions.eq(Empcontract.PROP_EMPLOYEE,
				contract.getEmployee()));
		detachedCriteria.add(Restrictions.eq(Empcontract.PROP_ETC_EXPIRE,
				contract.getEtcExpire()));
		detachedCriteria.add(Restrictions.eq(Empcontract.PROP_ECT_START_DATE,
				contract.getEctStartDate()));
		if (contract.getEctEndDate() != null)
			detachedCriteria.add(Restrictions.eq(Empcontract.PROP_ECT_END_DATE,
					contract.getEctEndDate()));
		int num = empContractDao.findRowCountByCriteria(detachedCriteria);
		if (num == 1)
			return 1;
		detachedCriteria = null;
		detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Empcontract.class);
		detachedCriteria.add(Restrictions.eq(Empcontract.PROP_EMPLOYEE,
				contract.getEmployee()));
		if (contract.getEtcExpire().intValue() == 1) {
			detachedCriteria.add(Restrictions.or(Restrictions.eq(
					Empcontract.PROP_ETC_EXPIRE, Integer.valueOf(1)),
					Restrictions.gt(Empcontract.PROP_ECT_END_DATE, contract
							.getEctStartDate())));
		} else {
			detachedCriteria.add(Restrictions.and(Restrictions.eq(
					Empcontract.PROP_ETC_EXPIRE, Integer.valueOf(1)),
					Restrictions.lt(Empcontract.PROP_ECT_START_DATE, contract
							.getEctEndDate())));
			detachedCriteria.add(Restrictions.and(Restrictions.eq(
					Empcontract.PROP_ETC_EXPIRE, Integer.valueOf(0)),
					Restrictions.or(Restrictions.and(Restrictions.ge(
							Empcontract.PROP_ECT_START_DATE, contract
									.getEctStartDate()), Restrictions.le(
							Empcontract.PROP_ECT_END_DATE, contract
									.getEctEndDate())), Restrictions.or(
							Restrictions.and(Restrictions.le(
									Empcontract.PROP_ECT_START_DATE, contract
											.getEctStartDate()), Restrictions
									.gt(Empcontract.PROP_ECT_END_DATE, contract
											.getEctStartDate())),
							Restrictions.and(Restrictions.lt(
									Empcontract.PROP_ECT_START_DATE, contract
											.getEctEndDate()), Restrictions.ge(
									Empcontract.PROP_ECT_END_DATE, contract
											.getEctEndDate()))))));
		}
		num = empContractDao.findRowCountByCriteria(detachedCriteria);
		return num <= 0 ? 0 : -1;
	}

	public boolean insertList(List conList) {
		if (conList.size() > 0)
			try {
				empContractDao.saveOrupdate(conList);
				Employee employee = ((Empcontract) conList.get(0))
						.getEmployee();
				empContractDao.saveOrupdate(employee);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		return true;
	}

	public IEmpContractDao getEmpContractDao() {
		return empContractDao;
	}

	public void setEmpContractDao(IEmpContractDao empContractDao) {
		this.empContractDao = empContractDao;
	}

	public void updateObj(Object obj) {
		empContractDao.updateObject(obj);
	}

	IEmpContractDao empContractDao;
}
